from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import traceback
from autoTest_ecshop_new.utils.log_util import logger

class BasePage():
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 5)

    ## 定位单个元素
    def find_element(self, locator):
        try:
            logger.info(f"定位元素{locator}")
            element = self.wait.until(EC.visibility_of_element_located(locator))
            logger.info(f"元素{locator}定位成功")
            return element
        except:
            logger.error(f"元素定位失败，失败原因如下：\n{traceback.format_exc()}")
            raise

    ## 定位一组元素
    def find_elements(self, locator):
        try:
            logger.info(f"定位元素{locator}")
            elements = self.wait.until(EC.visibility_of_all_elements_located(locator))
            logger.info(f"元素{locator}定位成功")
            return elements
        except:
            logger.error(f"元素定位失败，失败原因如下：\n{traceback.format_exc()}")
            raise

    ## 输入数据
    def input_data(self, locator, value):
        # 定位到输入框
        inputBox = self.find_element(locator)
        # 输入数据
        inputBox.clear()
        logger.info(f"输入的数据是：\n{value}")
        inputBox.send_keys(value)

    # 点击按钮
    def click_btn(self, locator):

        # 根据传入的定位器，找到按钮元素
        btn = self.find_element(locator)
        # 点击按钮
        btn.click()
        # 打印点击的按钮的定位器
        logger.info(f"点击了：\n{locator}")

    #获取文本信息
    def get_text(self, locator):
        # 打印获取元素locator的文本信息
        logger.info(f'获取元素{locator}的文本信息')

        # 根据locator找到元素
        element = self.find_element(locator)
        # 打印元素的文本信息
        logger.info(f'文本信息为: {element}')
        # 返回元素的文本信息
        return element.text
